
from typing import List
from sqlmodel import Field, SQLModel, Relationship
from sqlalchemy import event
from models.Base import BaseAndTime, StatusTypeEnum 
from models.common import get_current_time
from .Link import Admin_Role_Link, Role_Menu_Link


class assignParams(SQLModel):
    id: int = Field(title='角色ID')
    menuIds: List[int] = Field(title='菜单ID列表')
class create_role(SQLModel):
    name: str = Field(max_length=30,nullable=False,title='角色名字')
    code: str = Field(max_length=30,nullable=False,title='角色编码', unique=True)
    remark: str = Field(max_length=255,nullable=False,title='备注')
    status: StatusTypeEnum = Field(default=StatusTypeEnum.NORMAL,title='状态', index=True)
    parent_id: int = Field(nullable=False,index=True,title='父级ID')

class edit_role(create_role):
    id: int = Field(title='角色ID')

class Role(BaseAndTime,create_role, table=True):
    __tablename__ = "sys_role"  # 确保表名一致
    menus: List["Menu"] = Relationship(back_populates="roles", link_model=Role_Menu_Link)
    admins: List["Admin"] = Relationship(back_populates="roles", link_model=Admin_Role_Link)
    
    @property
    def status_text(self)->str:
        if self.status == StatusTypeEnum.NORMAL:
            return "正常"
        elif self.status == StatusTypeEnum.ABNORMAL:
            return "关闭"
        return "未知"

@event.listens_for(Role, 'before_update', propagate=True)
def timestamp_before_update(mapper, connection, target):
    target.updatetime = get_current_time()